import { reqGetCode, reqUSerRegister, reqUserLogin, reqUserInfo, reqLogout } from '@/api';
import { setToken, getToken, removeToken } from '@/utils/token.js';
//user模块小仓库
const state = {
  code: '',
  token: getToken(),
  userInfo: {}
}
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  USERLOGIN(state, token) {
    state.token = token
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  //退出登录，清除数据
  CLEAR(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  //获取验证码
  async getCode({ commit }, phone) {
    //由于经费问题，所以直接返回验证码
    let result = await reqGetCode(phone)
    if (result.code == 200) {
      commit('GETCODE', result.data)
    }
    else {
      return Promise.reject(new Error('faile'))
    }
  },
  //注册
  async reqUSerRegister({ commit }, user) {
    const result = await reqUSerRegister(user)
    if (result.code == 200) return 'ok'
    else return Promise.reject(new Error('faile'))
  },
  //登录[token]
  async userLingin({ commit }, data) {
    const result = await reqUserLogin(data)
    //存token
    if (result.code == 200) {
      commit('USERLOGIN', result.data.token)
      //持久化存储
      setToken(result.data.token)
      return 'ok'
    }
    else return Promise.reject(new Error('faile'))
  },
  //获取用户信息
  async getUserInfo({ commit }) {
    const result = await reqUserInfo()
    if (result.code == 200) {
      //提交用户信息
      commit('GETUSERINFO', result.data)
      return 'ok'
    }
    else {
      return Promise.reject(new Error(result.message))
    }
  },
  //退出登录
  async userLogout({ commit }) {
    const result = await reqLogout()
    if (result.code == 200) {
      commit('CLEAR')
      return 'ok'
    }
    else {
      return Promise.reject(new Error('faile'))
    }
  }

}
const getters = {

}

export default {
  state,
  mutations,
  actions,
  getters
}